<template>
	<view class="content">
		<NavigationTitle title="选择项目" style="color: #000;background: #fff;position: fixed;width: 100%;z-index: 100;">
			<template slot="left_con">
				<zb-popover placement="bottom-start" :options="setOption" ref="Popover1" @handleClick="handleClick"
					@select="selectSet" class="item-popover">
					<uni-icons type="gear" size="30"></uni-icons>
				</zb-popover>
			</template>
			<template slot="right_con">
				<uni-icons type="settings" size="30" @click="showDrawer()"></uni-icons>
			</template>
		</NavigationTitle>
		<view class="status-bar"></view>
		<!-- <view  class="mask-class" v-show="isMaskShow"></view > 
			<view class="user_search">
			<uni-data-select v-model="value" :clear="false" :localdata="option_search"
				@change="changeSel"></uni-data-select>
			<uni-search-bar class="search" radius="5" placeholder="搜索" clearButton="auto" cancelButton="none"
				@confirm="search" @clear="clearSear" />
		</view> -->
		<scroll-view class="preject" scroll-y="true" refresher-enabled="true" @refresherrefresh="doRefresh"
			@scrolltolower="scrolltoupper" :refresher-triggered="pullLoading">
			<view v-for="(item,index) in list" :key="item.sysProject.projId"
				@click.stop.prevent="()=>callBack('edit',item)">
				<!-- <text v-if="item.sysProject.totalMessage!=0" class="item_badge">
					{{item.sysProject.totalMessage<99?'99+':item.sysProject.totalMessage}}
				</text> -->
				<uni-badge style="width: 100%; margin-top: 36rpx;" :text="item.sysProject.totalMessage" absolute="rightTop" size="small">
						<view class="preject_item">
							<view class="item_top">
								<text class="item_name">{{item.sysProject.projName}}</text>
								<text class="item_date">{{getDate(item.sysProject.createTime)}}</text>
							</view>
							
							<view class="item">
								<text class="item_title">编号：</text>
								{{item.sysProject.projNumber}}
							</view>
							<view class="item">
								<text class="item_title">分类：</text>
								{{item.sysProject.projClassification||'暂无'}}
							</view>
							<view class="item">
								<text class="item_title">地区：</text>
								{{item.sysProject.projRegion||'暂无'}}
							</view>
							<view class="item">
								<text class="item_title">项目周期：</text>
								{{getDate(item.sysProject.projBeginTime)+" 至 "+getDate(item.sysProject.projEndTime)}}
							</view>
							<view class="item">
								<text class="item_title">项目状态：</text>
								{{item.sysProject.projStatus}}
							</view>
							<view class="item">
								<text class="item_title">创建人：</text>
								{{item.sysProject.creator}}
							</view>
						</view>
				</uni-badge>
				
				<!-- <view class="item_btn">
					<text class="btn" style="border-right: 1px solid #ccc;" @click="()=>callBack('edit',item)"> 项目详情 </text>
					<text class="btn" style="border-right: 1px solid #ccc;" @click.stop.prevent="()=>callBack('user',item)"> 人员管理 </text>
					<text class="btn" @click.stop.prevent="()=>callBack('equipment',item)"> 设备管理 </text>
				</view> -->
			</view>
			<uni-load-more :status='loadStatus' v-if="list&&list.length>3"></uni-load-more>
		</scroll-view>
		<uni-drawer ref="showLeft" mode="left" :width="320">
			<view class="status-bar"></view>
			<view class="drawerLeft">
				<uni-forms ref="baseForm" :modelValue="searchValue" label-position="top" class="baseForm">
					<uni-forms-item label="项目名称:">
						<uni-easyinput v-model="searchValue.projName" placeholder="请输入项目名称" />
					</uni-forms-item>
					<uni-forms-item label="项目状态:">
						<uni-data-select
						        v-model="searchValue.projStatus"
						        :localdata="[
									 { value: 0, text: '未审核' },
									{ value: 1, text: '已审核' },
								]"
								placeholder="请选择项目状态"
						      ></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="所属地区:">
						<uni-easyinput v-model="searchValue.projRegion" placeholder="请输入所属地区" />
					</uni-forms-item>
					<uni-forms-item label="详细地址:">
						<uni-easyinput v-model="searchValue.projAddress" placeholder="请输入详细地址" />
					</uni-forms-item>
					
				</uni-forms>
				<view class="popupBtn">
					<button type="primary" @click="drawerConfirm" class="btn">确定</button>
					<button type="reset" @click="drawerClose" class="btn">重置</button>
				</view>
			</view>
		</uni-drawer>
		<image v-if="authorList.includes('system_project_add')" src="@/static/common/advice_add.png" class="projectAdd" @click="addPreject"></image>
	</view>
</template>

<script>
	import NavigationTitle from '@/components/navigationTitle'
	import {
		showToastMsg,
		getUploadDate,
		showModalMsg
	} from '@/utils/format.js'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	export default {
		components: {
			NavigationTitle
		},
		computed: {
			...mapGetters(['roleList', 'roleTree', 'authorList', 'fileType', 'deviceType', 'deviceStatus'])
		},
		data() {
			return {
				value: 'projName',
				isMaskShow:false,
				searchValue: {},
				option_search: [{
						value: 'projName',
						text: "项目名称"
					},
					{
						value: 'projRegion',
						text: "所属地区"
					},
				],
				setOption: [
					{
						text: '扫一扫',
						id:1
					},
					{
						text: '退出',
						id:2
					},
				],
				ready: false,
				baseUrl: '',
				list: [],
				pageData: {
					pageSize: 10,
					pageNum: 1,

				},
				pullLoading: false,
				loadingType: 0, //加载状态
				isLoadingMore: false, // 是否正在加载更多
				loadStatus: 'more', // 是否还有更多数据
			}
		},
		onLoad() {
			this.getProjectList(this.pageData)
			// this.byNfcTest()
		},
		onShow() {
			this.save_author_list(uni.getStorageSync('author_list') || [])
			if (this.roleList.length == 0) this.getRoleAll()
			if (this.roleTree.length == 0) this.getRoleTree()
			if (this.fileType.length == 0) this.get_disCode('FILE_TYPE')
			if (this.deviceType.length == 0) this.get_disCode('DEVICE_TYPE')
			if (this.deviceStatus.length == 0) this.get_disCode('DEVICE_STATUS')
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			...mapActions(['get_roleAll', 'get_roleTree', 'save_project', 'save_project_id', 'save_author_list',
				'get_disCode'
			]),
			byNfcTest(){
				const ByUniPlugin = uni.requireNativePlugin('by-BYNFC-BYnfcModule')
				        //普通nfc读写      
				        //扫描方法
				        ByUniPlugin.StartScan({
				            'alertMessage': '开始准备扫描，请将标签贴近手机', //提示的信息
				        },
				        (ret) => {
				            uni.showToast({
				                title:'调用StartScan方法 ' + ret,//回调参数resultMsg、resultCode、payload、type、identifier、serialNumber
				                icon: "none"
				            })
				        })
				        //写入方法
				        ByUniPlugin.startwrite({
				            'alertMessage': '开始准备写入，请将标签贴近手机', //提示的信息
				            'nfcmsgs':[{
				                'type': 'U',// U ->ios 格式
				                'identifier': '123',
				                'payload': '/app包名或者链接地址或者小程序地址'//ios前面必须多加一个字符
				            },{
				                'type': 'ndroid.com:pkg',//ndroid.com:pkg  ->android打开app的包名格式
				                'identifier': '123',
				                'payload': 'app包名或者链接地址或者小程序地址'
				            }
				            ]
				
				        },
				        (ret) => {
				            uni.showToast({
				                title:'调用startwrite方法 ' + ret,//回调参数resultMsg、resultCode
				                icon: "none"
				            })
				        })
				
				        //16进制  数据块的读写
				        //扫描方法
				        ByUniPlugin.BlockScan({
				            'blockLength': '3',//长度
				            'blockIndex': '0',//地址
				        },
				        (ret) => {
				            uni.showToast({
				                title:'调用NfcScan方法 ' + ret.resultMsg,
				                icon: "none"
				            })
				        })
				        //写入方法
				        ByUniPlugin.BlockWrite({
				            'mesData': ['12','33','22','22'],//写入的内容
				            'blockLength': '3',//长度
				             'blockIndex': '0',//地址
				
				        },
				        (ret) => {
						console.log('xieru')
				        })
			},
			selectSet(e) {
				this.isMaskShow = false
				 if(e.id==1){
					this.qrCode()
				}else if(e.id==2){
					this.logout()
				}
				console.log(e)
			},
			handleClick(e) {
				this.isMaskShow = e
			},
			showDrawer() {
				this.$refs['showLeft'].open()
			},
			// 关闭窗口
			closeDrawer() {
				this.$refs['showLeft'].close()
			},
			drawerConfirm(){
				this.getProjectList({
					pageNum: 1,
					pageSize: 10,
				}, this.searchValue)
				this.closeDrawer()
			},
			drawerClose(){
				this.searchValue = {}
				this.getProjectList({
					pageNum: 1,
					pageSize: 10,
				}, null)
				this.closeDrawer()
			},
			logout() {
				showModalMsg('提示', '是否确定退出登录!', (res) => {
					if (res) {
						uni.reLaunch({
							url: '/pages/login/index'
						})
					} else return
				})

			},
			qrCode() {
				uni.scanCode({
					onlyFromCamera: true,
					success: (res) => {
						uni.navigateTo({
							url: '/pages/qrCode/index?' + res.result
						})
					},
					fail: () => {
						console.log('quxiao')
					}
				})
			},
			scrolltoupper() {
				this.getListMore({
					pageNum: this.pageData.pageNum + 1,
					pageSize: 10,
				}, this.searchValue)
			},
			doRefresh() {
				this.pullLoading = true;
				// 执行数据刷新的逻辑
				if (!this.pullLoading) return
				this.getProjectList({
					pageNum: 1,
					pageSize: 10,
				}, this.searchValue)
			},
			changeSel(e) {
				this.value = e
			},
			search(e) {
				let obj = {}
				obj[this.value] = e.value
				this.searchValue = obj
				this.getProjectList({
					pageNum: 1,
					pageSize: 10,
				}, obj)
			},
			clearSear() {
				this.searchValue = {}
				this.getProjectList({
					pageNum: 1,
					pageSize: 10,
				}, null)
			},
			getDate(date) {
				if (!date) return
				if (date.indexOf(" ") == "-1") return date
				let arr = date.split(" ")
				return arr[0]
			},
			callBack(type, data) {
				this.save_project({
					...data
				})
				this.save_project_id(data.sysProject.projId || '')
				if (type == 'user' && this.authorList.includes('system_user')) uni.navigateTo({
					url: '/pages/user/index'
				})
				else if (type == 'equipment' && this.authorList.includes('system_user')) uni.navigateTo({
					url: '/pages/equipment/index'
				})
				else if (type == 'edit') {
					uni.setStorageSync('projectType', 'edit');
					uni.switchTab({
						url: '/pages/prejectDetail/index?type=edit'
					})
				} else showToastMsg('无操作权限！')
				
				
			},
			addPreject() {
				uni.setStorageSync('projectType', 'add');
				uni.switchTab({
					url: '/pages/prejectDetail/index?type=add'
				})
			},
			async getProjectList(page, value) {
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
				let that = this
				let param = JSON.parse(JSON.stringify(page))
				if (value) {
					for (let key in value) {
						param[key] = value[key]
					}
				}
				const res = await this.$api.getProjectList(param).catch((err) => {
					console.log(err)
				})
				if (res.code == 200) {
					this.list = res.data.data
					this.pageData = page
					this.loadingType = 0;
				}
				setTimeout(() => {
					that.pullLoading = false;
				}, 500)
				uni.hideLoading()
				showToastMsg(res.msg)

			},
			async getListMore(page, value) {
				if (this.loadingType !== 0) return
				this.loadStatus = "loading"
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
				this.loadingType = 1
				let param = JSON.parse(JSON.stringify(page))
				if (value) {
					for (let key in value) {
						param[key] = value[key]
					}
				}
				await this.$api.getProjectList(param).then(res => {
					if (res?.code == 200) {
						if (res.data.data.length == 0) {
							this.loadingType = 2;
							this.loadStatus = "noMore"
							return
						} else if (res.data.data.length < 10) {
							this.loadingType = 2;
							this.loadStatus = "noMore"
						} else {
							this.loadingType = 0;
							this.loadStatus = "more"
						}
						this.list = this.list.concat(res.data.data)
						this.pageData = page
						uni.hideLoading()
					}
				})
			},
			async getRoleAll() {
				await this.get_roleAll();
				let result = this.roleList;
			},
			async getRoleTree() {
				await this.get_roleTree();
				let result = this.roleTree;
			},
			//检查版本更新情况
			checkVersion() {
				//模拟接口获取最新版本号，版本号固定为整数
				plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
					console.log(widgetInfo.versionCode)
					// this.$api.getLatest({}).then(res => {
					// 	if (res.code == 1) {

					if (Number(widgetInfo.versionCode) == 100) {
						// uni.navigateTo({url:"/pages/index/upgrade"})
						// let obj = {
						// 	version: "v" + res.data.version1
						// }
						// this.lastVersionInfo = obj
						// let downloadLink = res.data.name
						// let androidLink = this.baseUrl + "/Version/Update";
						// let iosLink = this.baseUrl + "/Version/Update";
						// let ready = this.ready
						if (plus.os.name.toLowerCase() == "ios") {
							uni.showModal({
								title: '发现新版本 ',
								content: '请到App store进行升级',
								showCancel: true,
								success: (res) => {
									console.log(res)
									if (res.cancel) {
										console.log("取消")
									} else if (res.confirm) {
										plus.runtime.openURL(
											"https://itunes.apple.com/app/6471469979"
										)
									} else return

								}
							})
						} else if (plus.os.name.toLowerCase() == "android") {
							if (downloadLink.match(RegExp(/.wgt/))) {
								if (androidLink && androidLink !== '#') {
									// 我这里默认#也是没有地址，请根据业务自行修改
									console.log('发现下载地址');
									// 安卓：创建下载任务
									if (downloadLink.match(RegExp(/.wgt/))) {
										console.log('确认wgt热更新包');
										this.downloadLink = androidLink;
										this.ready = true;
										this.versionShow = true
										uni.hideTabBar()
									} else {
										console.log('安卓推荐.wgt强制更新，.apk的强制更新请您自行修改程序');
									}
								} else {
									this.ready = false;
									console.log('下载地址是空的，无法继续');
								}
							} else {
								uni.navigateTo({
									url: './upgrade'
								})
							}
						}

					}

					// 	}
					// })
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import '@/assets/styles/global.scss';

	view {
		box-sizing: border-box;
	}

	.content {
		position: relative;
		height: 100vh;
	}

	.user_search {
		display: flex;
		padding: $System__title_height 12rpx 0;

		.search {
			flex: 7;
		}

		/deep/.uni-stat__select {
			flex: 3;
		}
	}

	.preject {
		height: 90vh;
		padding: $System__title_height 0 0;
		position: relative;

		/deep/ .uni-scroll-view-content {
			padding: 0 48rpx 50rpx;
			box-sizing: border-box !important;
		}

		.preject_item {
			min-height: 350rpx;
			background-color: #eee;
			border-radius: 20rpx;
			padding: 24rpx 0 0;
			// margin-top: 24rpx;
			// overflow: hidden;
			box-shadow: 0rpx 5rpx 10rpx 0rpx #F0F0F0;
			position: relative;
			.item_badge{
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				width: 55rpx;
				height: 55rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color:#fff;
				border-radius: 50%;
				background-color: red;
				box-shadow: 0rpx 5rpx 10rpx 0rpx #F0F0F0;
			}
			.item_top {
				display: flex;
				justify-content: space-between;
				padding: 0 24rpx;

				.item_name {
					font-size: 36rpx;
					font-weight: 600;
					width: 70%;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.item_date {
					flex: 1;
					font-size: 28rpx;
				}
			}

			.item {
				padding: 0 24rpx;
				font-size: 28rpx;
			}

			.item_btn {
				margin-top: 12rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-top: 1px solid #fff;
				background-color: #fff;

				.btn {
					width: 49%;
					padding: 24rpx 0;
					font-size: 32rpx;
					text-align: center;
					background-color: #fff;
					color: rgb(97, 86, 255);
				}
			}
		}
	}

	.drawerLeft {
		padding: 20rpx;

		.baseForm {
			padding: 20rpx 0;
			min-height: 50vh;
			/deep/ .uni-forms-item__label{
				font-size:28rpx;
			}
		}

		.popupBtn {
			display: flex;
			justify-content: space-between;
			margin-top: 20rpx;

			.btn {
				width: 45%;
			}
		}
	}

	.back_icon {
		width: 37rpx;
	}

	.projectAdd {
		width: 150upx;
		height: 150upx;
		border-radius: 50%;
		position: fixed;
		bottom: 150upx;
		right: 50upx;
	}
	.item-popover{
		z-index: 100;
	}
	.mask-class {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  background-color: rgba(0, 0, 0, 0.2);
	  z-index: 99;
	}
</style>